﻿using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Security.Claims;
using System.Threading.Tasks;
using Volo.Abp.Account.Web;
using Volo.Abp.Account.Web.Pages.Account;
using Volo.Abp.AspNetCore.Mvc.UI.RazorPages;
using Volo.Abp.Data;
using Volo.Abp.DependencyInjection;
using Volo.Abp.Identity;
using Volo.Abp.Security.Claims;

namespace YaAppoint.Web.Pages.Account
{
    [ExposeServices(typeof(LoginModel))]
    public partial class MyLoginModel :LoginModel
    {
        [Required(ErrorMessage = "用户名不能为空")]
        [BindProperty]
        [DisplayName("用户名")]
        public string UserName { get; set; }

        [BindProperty]
        [DisplayName("密码")]
        public string Password { get; set; }

        [Required(ErrorMessage = "请选择用户组")]
        [BindProperty]
        [DisplayName("科室")]
        public string Department { get; set; }

        [BindProperty]
        [DisplayName("记住我")]
        public bool RememberMe { get; set; }

        private readonly UserManager<Volo.Abp.Identity.IdentityUser> _userManager;
        private readonly SignInManager<Volo.Abp.Identity.IdentityUser> _signInManager;

        public MyLoginModel(
            IAuthenticationSchemeProvider schemeProvider,
            IOptions<AbpAccountOptions> accountOptions,
            IOptions<IdentityOptions> identityOptions,
            IdentityDynamicClaimsPrincipalContributorCache identityDynamicClaimsPrincipalContributorCache,
            UserManager<Volo.Abp.Identity.IdentityUser> userManager,
            SignInManager<Volo.Abp.Identity.IdentityUser> signInManager):base(schemeProvider,accountOptions, identityOptions, identityDynamicClaimsPrincipalContributorCache)
        {
            _userManager = userManager;
            _signInManager = signInManager;
        }
        public override async Task<IActionResult> OnPostAsync(string returnUrl = null)
        {
            if (ModelState.IsValid)
            {
                var user = await _userManager.FindByNameAsync(UserName);
                if (user != null)
                {
                    if (!user.GetProperty<bool>("IsActive"))
                    {
                        ModelState.AddModelError("", "用户已被禁用");
                    }
                    // 验证密码
                    var passwordValid = await _userManager.CheckPasswordAsync(user, Password);
                    if (passwordValid)
                    {
                        var claims = new List<Claim>();
                        claims.Add(new Claim(AbpClaimTypes.Name, user.Name));
                        var jobNumber = user.GetProperty<string>("JobNumber");
                        if (!string.IsNullOrEmpty(jobNumber))
                        {
                            claims.Add(new Claim("job-number", jobNumber));
                        }
                        var args = Department.Split('@');
                        if (args.Length > 0)
                        {
                            claims.Add(new Claim("department-name", args[0]));
                            claims.Add(new Claim("deparment-id", args[1]));
                        }

                        var authProps = new AuthenticationProperties
                        {
                            IsPersistent = RememberMe,
                            ExpiresUtc = DateTimeOffset.UtcNow.AddHours(24)
                        };

                        if (RememberMe)
                        {
                            authProps.ExpiresUtc = DateTimeOffset.UtcNow.AddDays(15);
                        }
                        await _signInManager.SignInWithClaimsAsync(user, authProps, additionalClaims: claims);
                    }
                    else
                    {
                        ModelState.AddModelError("", "密码不正确");
                    }
                }
                else
                {
                    ModelState.AddModelError("", "用户不存在");
                }
            }

            return Page();
        }
    }

}


